package com.innovation.chengzhangriji.ui.widget;

import android.Manifest;
import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.StateListDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.animation.SlideInUpAnimator;
import com.innovation.chengzhangriji.util.FileUtils;

import java.io.File;
import java.io.IOException;

public class TimeLineBarView extends RelativeLayout implements View.OnClickListener, View.OnTouchListener {

    public interface SendMessageListener {

        void sendMessage(String text);

    }

    public interface ExecuteListener {

        void execute(int position);

    }

    public interface RecordListener {

        void start();

        void success(int length, String path);

        void timing(int length);

        void failure();

        void cancel();

    }

    private static final int DURATION = 200;

    private SendMessageListener mSendMessageListener;

    private ExecuteListener mExecuteListener;

    private RecordListener mRecordListener;

    private CuteImageView mCivRecordOrKeyboard;
    private CuteImageView mCivMore;
    private CuteImageView mCivEmoji;
    private CuteEditText mCetInput;
    private CuteButton mCbRecord;
    private StateListDrawable drawable;
    private FrameLayout mEmojiGroup;
    private FrameLayout mMoreGroup;
    private InputMethodManager imm;

    // false 表示为键盘状态, true 表示为录音状态
    private boolean isRecord;

    // false 表示为发送状态, true 表示为更多状态
    private boolean isMore = true;

    // false 表示未展开表情组件, true 表示展开表情组件
    private boolean expandEmoji;

    // false 表示未展开更多组件, true 表示展开更多组件
    private boolean expandMore;

    // 是否是第一次打开软键盘
    private boolean isFirstOpenKeyboard;

    // 表情高度
    private float emoji_height;

    // 更多高度
    private float more_height;

    public TimeLineBarView(Context context) {
        super(context);
        init(context);
    }

    public TimeLineBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TimeLineBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_record_or_keyboard:
                close();
                if (isRecord) {
                    // 切换为键盘状态
                    isRecord = false;
                    mCivRecordOrKeyboard.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_audio));
                    mCetInput.setVisibility(View.VISIBLE);
                    mCbRecord.setVisibility(View.GONE);
                    mCivEmoji.setVisibility(View.VISIBLE);
                    if (mCetInput.getText().length() > 0) {
                        mCivMore.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_send));
                        isMore = false;
                    }
                } else {
                    // 切换为录音状态
                    isRecord = true;
                    mCivRecordOrKeyboard.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_keyboard));
                    mCetInput.setVisibility(View.GONE);
                    mCbRecord.setVisibility(View.VISIBLE);
                    mCivEmoji.setVisibility(View.GONE);
                    closeKeyboard();
                    mCivMore.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_more));
                    isMore = true;
                }
                break;
            case R.id.image_more:
                if (isMore) {
                    if (expandMore) {
                        close();
                    } else {
                        closeKeyboard();
                        expandMore();
                    }
                } else {
                    sendMessage();
                    isMore = true;
                    mCivMore.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_more));
                    mCetInput.setText(null);
                }
                break;
            case R.id.image_emoji:
                if (expandEmoji) {
                    close();
                } else {
                    closeKeyboard();
                    expandEmoji();
                }
                break;
        }
    }

    private long firstTime;

    @Override
    public boolean onTouch(View v, MotionEvent ev) {
        if (mRecordListener == null) {
            return false;
        }
        if (v.getId() == R.id.btn_record) {
            final int action = MotionEventCompat.getActionMasked(ev);
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    mCbRecord.setText("松开结束");
                    drawable.setColorFilter(getResources().getColor(R.color.bottom_bar_bg), PorterDuff.Mode.MULTIPLY);
                    if (firstTime == 0) {
                        firstTime = System.currentTimeMillis();
                    } else {
                        long secondTime = System.currentTimeMillis();
                        if (secondTime - firstTime < 2000) {
                            return false;
                        } else {
                            firstTime = secondTime;
                        }
                    }
                    new Thread(new RecorderRunnable()).start();
                    break;
                case MotionEvent.ACTION_MOVE:
                    final float y = MotionEventCompat.getY(ev, 0);
                    cancel = y < -320;
                    if (cancel) {
                        mCbRecord.setText("松开手指,取消发送");
                    } else {
                        mCbRecord.setText("松开结束");
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    mCbRecord.setText("按住录音");
                    drawable.clearColorFilter();
                    record = false;
                    break;
            }
            return true;
        }
        return false;
    }

    private boolean record;

    private boolean cancel;

    private int length;

    private String path;

    private Handler mHandler = new Handler();

    private class RecorderRunnable implements Runnable {

        private static final int SLEEP = 1000;

        @Override
        public void run() {
            record = true;
            length = 0;
            // 检测权限
            if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getContext(), "录音失败,请在系统设置的权限管理里打开录音权限", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
//                intent.setData(uri);
//                getContext().startActivity(intent);
                return;
            }
            /*录音*/
            MediaRecorder mRecorder = new MediaRecorder();
            try {
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mRecorder.setAudioSamplingRate(8000);
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                File file = Config.createFile(getContext(),Config.AUDIO_DIR);
                path = file.getPath();
                mRecorder.setOutputFile(path);
                mRecorder.prepare();
                mRecorder.start();
            } catch (IOException | IllegalStateException e) {
                e.printStackTrace();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "录音失败,请在系统设置的权限管理里打开录音权限", Toast.LENGTH_SHORT).show();
//                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                        Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
//                        intent.setData(uri);
//                        getContext().startActivity(intent);
                    }
                });
                mRecorder.reset();
                mRecorder.release();
                mRecorder = null;
                FileUtils.deleteFile(path);
                return;
            }

            while (record && length < Config.AUDIO_MAX_LENGTH) {
                try {
                    length++;
                    if (cancel) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                mRecordListener.cancel();
                            }
                        });
                    } else {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                mRecordListener.timing(Config.AUDIO_MAX_LENGTH - length);
                            }
                        });
                    }
                    Thread.sleep(SLEEP);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 结束
            if (mRecorder != null) {
                mRecorder.reset();
                mRecorder.release();
            }

            if (cancel) {
                cancel = false;
                FileUtils.deleteFile(path);
            } else {
                if (length >= 1) {
                    post(new Runnable() {
                        @Override
                        public void run() {
                            mRecordListener.success(length, path);
                        }
                    });
                } else {
                    FileUtils.deleteFile(path);
                    post(new Runnable() {
                        @Override
                        public void run() {
                            mRecordListener.failure();
                        }
                    });
                }
                cancel = false;
            }

        }
    }

    public void setSendMessageListener(SendMessageListener sendMessageListener) {
        mSendMessageListener = sendMessageListener;
    }

    public void setExecuteListener(ExecuteListener executeListener) {
        mExecuteListener = executeListener;
    }

    public void setRecordListener(RecordListener recordListener) {
        mRecordListener = recordListener;
    }

    private void init(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.layout_timeline_bar, this);
        mCivRecordOrKeyboard = (CuteImageView) view.findViewById(R.id.image_record_or_keyboard);
        mCivMore = (CuteImageView) view.findViewById(R.id.image_more);
        mCivEmoji = (CuteImageView) view.findViewById(R.id.image_emoji);
        mCetInput = (CuteEditText) view.findViewById(R.id.edit_input);
        mCbRecord = (CuteButton) view.findViewById(R.id.btn_record);
        mEmojiGroup = (FrameLayout) view.findViewById(R.id.layout_emoji);
        mMoreGroup = (FrameLayout) view.findViewById(R.id.layout_more);
        GridView emojiGrid = (GridView) view.findViewById(R.id.grid_emoji);
        GridView functionGrid = (GridView) view.findViewById(R.id.grid_more);

        drawable = new StateListDrawable();
        drawable.addState(new int[]{}, mCbRecord.getBackground());
        mCbRecord.setBackgroundDrawable(drawable);

        mCbRecord.setOnTouchListener(this);
        mCivRecordOrKeyboard.setOnClickListener(this);
        mCivMore.setOnClickListener(this);
        mCivEmoji.setOnClickListener(this);

        mCetInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mCivMore.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_send));
                    isMore = false;

                } else {
                    mCivMore.setCuteImageDrawable(getResources().getDrawable(R.mipmap.icon_more));
                    isMore = true;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mCetInput.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFirstOpenKeyboard) {
                    isFirstOpenKeyboard = true;
                    close();
                }
            }
        });

        emojiGrid.setAdapter(new EmojiAdapter());
        emojiGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                insertEmoji(position);
            }
        });


        functionGrid.setAdapter(new FunctionAdapter());
        functionGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                execute(position);
            }
        });

        imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        emoji_height = getResources().getDimension(R.dimen.timeline_bar_emoji_height);
        more_height = getResources().getDimension(R.dimen.timeline_bar_more_height);

    }

    private void sendMessage() {
        if (mSendMessageListener != null) {
            mSendMessageListener.sendMessage(mCetInput.getText().toString());
        }
    }

    // 关闭软键盘
    private void closeKeyboard() {
        imm.hideSoftInputFromWindow(mCetInput.getWindowToken(), 0);
        isFirstOpenKeyboard = false;
    }

    // 关闭展开的组件
    public void close() {
        expandEmoji = false;
        expandMore = false;
        moveView(this, DURATION, more_height);
    }

    // 展开表情组件
    private void expandEmoji() {
        if (!expandMore && !expandEmoji) {
            expandEmojiHelper();
            moveView(this, DURATION, emoji_height);
        } else if (expandMore && !expandEmoji) {
            moveView(this, DURATION, emoji_height, new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    expandEmojiHelper();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
    }

    private void expandEmojiHelper() {
        expandEmoji = true;
        expandMore = false;
        mEmojiGroup.setVisibility(View.VISIBLE);
        mMoreGroup.setVisibility(View.INVISIBLE);
    }

    // 展开更多组件
    private void expandMore() {
        expandEmoji = false;
        expandMore = true;
        mEmojiGroup.setVisibility(View.INVISIBLE);
        mMoreGroup.setVisibility(View.VISIBLE);
        moveView(this, DURATION, 0);
    }

    private void moveView(View view, int duration, float targetY) {
        SlideInUpAnimator slideInUpAnimator = new SlideInUpAnimator();
        slideInUpAnimator.setTargetY(targetY);
        slideInUpAnimator.prepare(view);
        slideInUpAnimator.setDuration(duration);
        slideInUpAnimator.start();
    }

    private void moveView(View view, int duration, float targetY, Animator.AnimatorListener l) {
        SlideInUpAnimator slideInUpAnimator = new SlideInUpAnimator();
        slideInUpAnimator.setTargetY(targetY);
        slideInUpAnimator.prepare(view);
        slideInUpAnimator.setDuration(duration);
        slideInUpAnimator.start();
        slideInUpAnimator.addAnimatorListener(l);
    }

    private void insertEmoji(final int position) {
        String text = getResources().getString(Config.EMOJIS[position]);
        int index = mCetInput.getSelectionStart();
        Editable editable = mCetInput.getText();
        editable.insert(index, text);
    }

    private void execute(int position) {
        if (mExecuteListener != null) {
            mExecuteListener.execute(position);
        }
    }

    private class EmojiAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return Config.EMOJIS.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) TimeLineBarView.this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_timeline_bar_emoji, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.emoji_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.imageView.setImageResource(Config.EMOJIS_DRAWABLE[position]);

            return convertView;
        }

        class ViewHolder {
            ImageView imageView;
        }
    }

    private class FunctionAdapter extends BaseAdapter {

        final String[] FUNCTION_TEXT = new String[] { "照片", "拍照", "小视频", "第一次" };

        @Override
        public int getCount() {
            return Config.FUNCTION_DRAWABLE.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) TimeLineBarView.this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_timeline_bar_function, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (CuteTextView) convertView.findViewById(R.id.function_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.imageView.setCompoundDrawablesWithIntrinsicBounds(0, Config.FUNCTION_DRAWABLE[position], 0, 0);
            viewHolder.imageView.setText(FUNCTION_TEXT[position]);

            return convertView;
        }

        class ViewHolder {
            CuteTextView imageView;
        }
    }
}
